package com.shundr.user;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.R;
import com.shundr.base.BaseActivity;
import com.shundr.common.model.PictureInfo;
import com.shundr.common.util.Base64Util;
import com.shundr.common.util.JsonUtil;
import com.shundr.common.util.LImageLoader;
import com.shundr.common.util.PictureUtil;
import com.shundr.common.util.ProgressDialogHelper;
import com.shundr.common.util.ToastHelper;
import com.shundr.frame.constant.LConstants;
import com.shundr.frame.constant.LContext;
import com.shundr.frame.http.LHttpRequest;
import com.shundr.frame.util.LLogger;
import com.shundr.frame.util.StringUtil;
import com.shundr.user.http.UserRequest;
import com.shundr.user.model.UserInfo;
import com.shundr.user.util.UserUtil;

/**
 * 用户认证
 * UserAuthActivity
 * 
 * @author larry 2015-4-23 上午9:44:36 
 * @version 1.0.0
 *
 */
public class UserReAuthActivity extends BaseActivity implements OnClickListener{
	
	private TextView tvStatus;
	
	private EditText etName;
	private EditText etID;
	
	private RelativeLayout layoutDriver;
	private ImageView btnDriver;
	
	private Button btnConfirm;
	
	private PictureInfo mPTruckInfo;//营运证
	/**
	 * 是否提交认证
	 */
	private boolean dot=false;
	
	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();
	
	private int flag = 0;
	
	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";
	
	private int mStatus = 0;
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case UserRequest.COMMIT_RE_AUTH_SUCCESSED:
				ProgressDialogHelper.dismiss();
				dot=true;
				ToastHelper.toastLong(mContext, "认证提交成功,会在一个工作日内审核,请耐心等待");
				new UserRequest(mContext, mHandler).getUserInfoByToken();
				new Timer().schedule(new TimerTask() {
					
					@Override
					public void run() {
						setResult(501);
						finish();
					}
				}, 1000);
				break;
			case UserRequest.GET_USER_DETAIL_INFO_SUCCESSED:
				UserInfo info = (UserInfo) msg.obj;
				UserUtil.saveUserToLocal(mContext, info, null);
				break;
			case LHttpRequest.REQUEST_FAILED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(mContext, (String)msg.obj);
				break;

			default:
				break;
			}
		}
		
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_auth_driver);
		tvStatus = (TextView)findViewById(R.id.tv_status);
		etName = (EditText)findViewById(R.id.et_name);
		etID = (EditText)findViewById(R.id.et_ID);
		
		btnDriver = (ImageView)findViewById(R.id.btn_driver);
		btnDriver.setOnClickListener(this);
		
		layoutDriver = (RelativeLayout)findViewById(R.id.layout_driver);
		layoutDriver.setOnClickListener(this);
		
		btnConfirm = (Button)findViewById(R.id.btn_confirm);
		btnConfirm.setOnClickListener(this);
		btnConfirm.setVisibility(View.VISIBLE);
		
		mStatus = LContext.userInfo.getIdValidationStatus();
		
		if(mStatus != 0 && mStatus != 3){
			etName.setEnabled(false);
			etID.setEnabled(false);
			layoutDriver.setClickable(false);
			btnConfirm.setVisibility(View.INVISIBLE);
		}else{
			etName.setEnabled(true);
			etID.setEnabled(true);
			layoutDriver.setClickable(true);
			btnConfirm.setVisibility(View.VISIBLE);
		}
		
		initData();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable("mPTruckInfo", mPTruckInfo);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mPTruckInfo = (PictureInfo) savedInstanceState.getSerializable("mPTruckInfo");
		
		if (mPTruckInfo != null) {
			ImageLoader.getInstance().displayImage("file://" + mPTruckInfo.getFilename(), btnDriver,LImageLoader.mOptions);
		}
		
		clearFocus();
	}
	
	private void initData(){
		try {
			UserInfo info = LContext.userInfo;
			etName.setText(info.getUserName());
			etID.setText(info.getUserCitizenNumber());
			ImageLoader.getInstance().displayImage(info.getUserDriverPic(), btnDriver,LImageLoader.mOptions);
			if(info.getIdValidationStatus() == 3){
				tvStatus.setVisibility(View.VISIBLE);
				tvStatus.setText(info.getIdValidationMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private boolean check(){
		if(StringUtil.isNull(etName.getText().toString())){
			ToastHelper.toastShort(mContext, "请填写真实姓名");
			return false;
		}
		if(StringUtil.isNull(etID.getText().toString())){
			ToastHelper.toastShort(mContext, "请填写身份证号码");
			return false;
		}
		if(!StringUtil.checkIDCard(etID.getText().toString())){
			ToastHelper.toastShort(mContext, "请填写正确的身份证号码");
			return false;
		}
//		if(mPIDInfo == null){
//			ToastHelper.toastShort(mContext, "请选择身份证件");
//			return false;
//		}
//		if(mPTruckInfo == null){
//			ToastHelper.toastShort(mContext, "请选择驾驶证");
//			return false;
//		}
		return true;
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			try {
				Uri data2 = null;
				if (data == null) {
					data2 = PictureUtil.getImageUri();
				} else {
					data2 = data.getData();
				}
				String outPic = "";
				switch (requestCode) {
				case PictureUtil.PHOTO_PICKED_WITH_DATA:
					outPic = PictureUtil.getRealFilePath(mContext, data2);
					outPic = PictureUtil.compressJpgImage(outPic);
					break;
				case PictureUtil.CAMERA_WITH_DATA:
					outPic = PictureUtil.compressJpgImage(LConstants.TEMP_PIC_PATH);
					break;
				case PictureUtil.PHOTO_CROP:
					break;
				default:
					break;
				}
				
				if (!new File(outPic).exists()) {
					ToastHelper.toastShort(mContext, getResources().getString(R.string.image_error));
					return;
				}
				
				Bitmap bitmap = BitmapFactory.decodeFile(outPic);
				PictureInfo info = new PictureInfo();
				info.setFileBase64Body(Base64Util.encodeImage(bitmap));
				info.setFilename(outPic);
				bitmap.recycle();
				if (flag == 0) {
					info.setType(PictureInfo.FileType.truck);
					mPTruckInfo = info;
					ImageLoader.getInstance().displayImage("file://" + outPic, btnDriver,LImageLoader.mOptions);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
//		getSupportMenuInflater().inflate(R.menu.menu_confirm, menu);
//		menu.getItem(0).setTitle("提交");
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_confirm:
			if (check()) {
				ProgressDialogHelper.show(mContext, "正在提交认证,请稍后...");
				mPictures.clear();
				if (mPTruckInfo != null) {
					mPictures.add(mPTruckInfo);
				}
				String json = JsonUtil.toJson(mPictures);
				LLogger.e(json);
				new UserRequest(mContext, mHandler).commitReAuth(etName
						.getText().toString(), etID.getText().toString(), json);
			}
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void clearFocus(){
		etName.clearFocus();
		etID.clearFocus();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_driver:
			flag = 0;
			PictureUtil.doPickPhotoAction(this);
			break;
		case R.id.btn_driver:
			try {
				if (mPTruckInfo != null) {
					ArrayList<String> list = new ArrayList<String>();
					if (!StringUtil.isNull("file://" + mPTruckInfo.getFilename())) {
						list.add("file://" + mPTruckInfo.getFilename());
					}
					if (list.size() > 0) {
						openImageReview(mContext, 0, list);
					}
				}else{
					if (LContext.userInfo != null) {
						ArrayList<String> list = new ArrayList<String>();
						if (!StringUtil.isNull(LContext.userInfo.getUserDriverPic())) {
							list.add(LContext.userInfo.getUserDriverPic());
						}
						if (list.size() > 0) {
							openImageReview(mContext, 0, list);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.btn_confirm:
			if (check()) {
				ProgressDialogHelper.show(mContext, "正在提交认证,请稍后...");
				mPictures.clear();
				if (mPTruckInfo != null) {
					mPictures.add(mPTruckInfo);
				}
				String json = JsonUtil.toJson(mPictures);
				LLogger.e(json);
				new UserRequest(mContext, mHandler).commitReAuth(etName
						.getText().toString(), etID.getText().toString(), json);
			}
			break;
		default:
			break;
		}
		
	}

	@Override
	protected void onDestroy() {
		if(dot){
			setResult(333);
		}
		super.onDestroy();
	}
}
